import { ref } from 'vue'
import { defineStore } from 'pinia'
import { LocalStorage } from '@/utils/use-storage'
import { UserInfoVo } from '@/types/user'
import { checkAuth, getMyInfo } from '@/api/users'
import defaultAvatar from '@/assets/images/default-avatar.png'

// 设置用户信息的默认值（头像等）
function userInfoDefault(obj: UserInfoVo ): UserInfoVo {
    const data = {...obj}
    data.avatar = data.avatar || defaultAvatar
    data.follower = data.follower || 0
    data.following = data.following || 0
    data.gender = data.gender || 3
    return data
}

export const useUserStore = defineStore('user', () => {
    // 用户token
    const accessToken = ref<string>('')
    // 是否登录
    const isLogin = ref<boolean>(false)
    // 我的信息
    const myInfo = ref<UserInfoVo>()
    // 用户信息
    const userInfo = ref<UserInfoVo>()
    // 初始化从llocalStorage取token并设置
    const setToken = (): void => {
        const token = LocalStorage.get('accessToken')
        if (token) {
            accessToken.value = token
            isLogin.value = true
        }
    }
    // 设置用户信息
    const setMyInfo = async (): Promise<void> => {
        if (!accessToken.value) return
        try {
            await checkAuth()
            const res = await getMyInfo()
            if (res) {
                myInfo.value = userInfoDefault(res.data)
                userInfo.value = userInfoDefault(res.data)
            }
        } catch (e) {
            isLogin.value = false
        }
    }
    // 设置用户信息
    const setUserInfo = async (): Promise<void> => {

    }
    return {
        accessToken,
        isLogin,
        myInfo,
        userInfo,
        setToken,
        setMyInfo,
    }
})
